//
//  TheGlobalMethod.m
//  FamilyTreasure
//
//  Created by apple on 16/4/12.
//  Copyright © 2016年 wypMIFAN. All rights reserved.
//

#import "TheGlobalMethod.h"

@interface TheGlobalMethod () 



@end

@implementation TheGlobalMethod



//cell
+ (id)setCell:(NSString *)cellName {
    UITableViewCell *cell;
    if ([[[[NSBundle mainBundle] loadNibNamed:cellName owner:nil options:nil] firstObject] isKindOfClass:[UITableViewCell class]]) {
        cell = [[[NSBundle mainBundle] loadNibNamed:cellName owner:nil options:nil] firstObject];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    } else {
        return [[[NSBundle mainBundle] loadNibNamed:cellName owner:nil options:nil] firstObject];
    }
    return cell;
}

//storyboard
+ (id)setstoryboard:(NSString *)vcName controller:(UIViewController *)vc {
    
    return [vc.storyboard instantiateViewControllerWithIdentifier:vcName];
}


+ (NSString *)dateWithStr:(NSString *)string Format:(NSString *)Format{
    NSString *str=string;//时间戳
    NSTimeInterval time=[str doubleValue];
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:Format];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    return currentDateStr;
}

//根据时间戳获取时间
+ (NSString *)dateStr:(NSString *)str666 {
    NSString *str=str666;//时间戳
    NSTimeInterval time=[str doubleValue];
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    return currentDateStr;
}

//根据时间戳获取时间
+ (NSString *)dateStrss:(NSString *)str666 {
    NSString *str=str666;//时间戳
    NSTimeInterval time=[str doubleValue];
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    return currentDateStr;
}

+ (CGFloat)theStringOfLabel:(NSString *)string width:(CGFloat)width labelSize:(NSInteger)labelSize{
    CGSize size = [string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:labelSize]} context:nil].size;
    return size.height;
}

+ (NSString *)timeStamp:(NSString *)str {
    //实例化一个NSDateFormatter对象
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //设定时间格式,这里可以设置成自己需要的格式
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    //设置GMT市区，保证转化后日期字符串与日期一致
    
    NSTimeZone *timezone = [[NSTimeZone alloc] initWithName:@"GMT"];
    
    [dateFormatter setTimeZone:timezone];
    
    //转化date为日期字符串
    
    NSDate *date = [dateFormatter dateFromString:str];
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]-3600*8];
    return timeSp;
}


//获取数据库
+ (id)getUserDefault:(NSString *)userMessage {
    return [[NSUserDefaults standardUserDefaults] objectForKey:userMessage];
}

//插入数据库
+ (void)insertUserDefault:(id)userMessage Key:(NSString *)key{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:userMessage forKey:key];
    [user synchronize];
}


+ (void)xianShiAlertView:(NSString *)xinXiStr controller:(UIViewController *)controller {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:xinXiStr preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:nil];
    [alert  addAction:action];
    [controller presentViewController:alert animated:YES completion:nil];
}

+ (void)popAlertView:(NSString *)xinxiStr controller:(UIViewController *)controller {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:xinxiStr preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [controller.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:action];
    [controller presentViewController:alert animated:YES completion:nil];
}

+ (void)popTAlertView:(NSString *)xinxiStr controller:(UIViewController *)controller {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:xinxiStr preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [controller.navigationController popToRootViewControllerAnimated:YES];
    }];
    [alert addAction:action];
    [controller presentViewController:alert animated:YES completion:nil];
}

+ (void)selectAlertView:(NSString *)xinXiStr controller:(UIViewController *)controller select:(SelectAlertViewBlock)block {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:xinXiStr preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        block();
    }];
    [alert  addAction:action];
    [controller presentViewController:alert animated:YES completion:nil];
}

+ (void)InWindowAlertView:(NSString *)xinXiStr {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:xinXiStr preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    [alertController addAction:cancelAction];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
}



+ (void)SpringAnimation:(UIView *)Controls {
    CGPoint cender = Controls.center;
    cender.x -= 10;
    Controls.center = cender;
    
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.1 initialSpringVelocity:100 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        //1.往右移动50
        CGPoint cender = Controls.center;
        cender.x += 10;
        Controls.center = cender;
        //2.放大1.2倍
        //        topLabel.transform = CGAffineTransformScale(topLabel.transform, 1.2, 1.2);
        
    } completion:^(BOOL finished) {
    }];
}

+ (void)SprTopBottom:(UIView *)Controls value:(CGFloat)value{
    CGPoint cender = Controls.center;
    if (value > 0) {
       cender.y = cender.y - value;
    } else {
       cender.y = cender.y + value;
    }
    
    NSLog(@"%f", cender.y);
    
    //Controls.center = cender;
    
    
    [UIView animateWithDuration:0.5 animations:^{
        Controls.center = cender;
    }];
}

+ (BOOL)showMessageReturn:(id)Controls text:(NSString *)text vc:(UIViewController *)vc{
    if ([Controls isKindOfClass:[UITextField class]]) {
        if ([(UITextField*)Controls text].length == 0) {
            [self xianShiAlertView:text controller:vc];
            return YES;
        } else {
            return NO;
        }
    } else if ([Controls isKindOfClass:[UILabel class]]) {
        if ([(UILabel*)Controls text].length == 0) {
            [self xianShiAlertView:text controller:vc];
            return YES;
        } else {
            return NO;
        }
    } else if ([Controls isKindOfClass:[UITextView class]]) {
        if ([(UITextView*)Controls text].length == 0) {
            [self xianShiAlertView:text controller:vc];
            return YES;
        } else {
            return NO;
        }
    }
    return YES;
}

+ (NSString *)distanceTimeWithBeforeTime:(double)beTime
{
    NSTimeInterval now = [[NSDate date]timeIntervalSince1970];
    double distanceTime = now - beTime;
    NSString * distanceStr;
    
    NSDate * beDate = [NSDate dateWithTimeIntervalSince1970:beTime];
    NSDateFormatter * df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"HH:mm"];
    NSString * timeStr = [df stringFromDate:beDate];
    
    [df setDateFormat:@"dd"];
    NSString * nowDay = [df stringFromDate:[NSDate date]];
    NSString * lastDay = [df stringFromDate:beDate];
    
    if (distanceTime < 60) {//小于一分钟
        distanceStr = @"刚刚";
    }
    else if (distanceTime <60*60) {//时间小于一个小时
        distanceStr = [NSString stringWithFormat:@"%ld分钟前",(long)distanceTime/60];
    }
    else if(distanceTime <24*60*60 && [nowDay integerValue] == [lastDay integerValue]){//时间小于一天
        distanceStr = [NSString stringWithFormat:@"今天 %@",timeStr];
    }
    else if(distanceTime<24*60*60*2 && [nowDay integerValue] != [lastDay integerValue]){
        
        if ([nowDay integerValue] - [lastDay integerValue] ==1 || ([lastDay integerValue] - [nowDay integerValue] > 10 && [nowDay integerValue] == 1)) {
            distanceStr = [NSString stringWithFormat:@"昨天 %@",timeStr];
        }
        else{
            [df setDateFormat:@"MM-dd HH:mm"];
            distanceStr = [df stringFromDate:beDate];
        }
        
    }
    else if(distanceTime <24*60*60*365){
        [df setDateFormat:@"MM-dd HH:mm"];
        distanceStr = [df stringFromDate:beDate];
    }
    else{
        [df setDateFormat:@"yyyy-MM-dd HH:mm"];
        distanceStr = [df stringFromDate:beDate];
    }
    return distanceStr;
}

+ (void)showMessage:(NSString *)message alpha:(CGFloat)alphaValue time:(CGFloat)time
{
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    UIView *showview =  [[UIView alloc]init];
    showview.tag = 30000;
    showview.backgroundColor = [UIColor blackColor];
    showview.frame = CGRectMake(0, 0, WIDTH_K, HEIGHT_K);
    showview.alpha = alphaValue;
    showview.userInteractionEnabled = YES;
    UITapGestureRecognizer *exitTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(exitView)];
    [showview addGestureRecognizer:exitTap];
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc]init];
    CGSize LabelSize = [message sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(290, 9000)];
    label.tag = 30001;
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor blackColor];
    label.alpha = 0.6;
    
    label.layer.cornerRadius = 5.0f;
    label.layer.masksToBounds = YES;
    label.font = [UIFont boldSystemFontOfSize:15];
    label.numberOfLines = 0;
    label.frame = CGRectMake(20, HEIGHT_K/2 - LabelSize.height/2, WIDTH_K-40, LabelSize.height+20);
    [window addSubview:label];
    
    if (time > 0) {

    [UIView animateWithDuration:1.5 animations:^{
        //        showview.alpha = 0;
        showview.alpha = 0;
        label.alpha=0;
        
    } completion:^(BOOL finished) {
        //        [showview removeFromSuperview];
        [showview removeFromSuperview];
        [label removeFromSuperview];
    }];
    }
}
+ (void)exitView {
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    [[window viewWithTag:30000] removeFromSuperview];
    [[window viewWithTag:30001] removeFromSuperview];
}

+(NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}

+(NSString*)getCurrentTimesOne{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"ss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}

//友盟
//+ (void)share:(UIViewController *)vc {
//    //显示分享面板
//    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
//        // 根据获取的platformType确定所选平台进行下一步操作
//        [self shareWebPageToPlatformType:platformType vc:vc];
//    }];
//}

//+ (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType vc:(UIViewController *)vc {
//    //创建分享消息对象
//    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
//    
//    //创建网页内容对象
//    //    NSString* thumbURL =  @"https://mobile.umeng.com/images/pic/home/social/img-1.png";
//    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"动物直播" descr:@"动物直播 - 宠物养成直播平台" thumImage:[UIImage imageNamed:@"Logo"]];
//    //设置网页地址
//    NSString *new_url=[@"http://www.zoostv.com/" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    shareObject.webpageUrl = new_url;
//    
//    //分享消息对象设置分享内容对象
//    messageObject.shareObject = shareObject;
//    
//    //调用分享接口
//    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:vc completion:^(id data, NSError *error) {
//        if (error) {
//            UMSocialLogInfo(@"************Share fail with error %@*********",error);
//        }else{
//            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
//                UMSocialShareResponse *resp = data;
//                //分享结果消息
//                UMSocialLogInfo(@"response message is %@",resp.message);
//                //第三方原始返回的数据
//                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
//                
//            }else{
//                UMSocialLogInfo(@"response data is %@",data);
//            }
//        }
//        NSLog(@"fenxiang:%@", error);
//        //        [self alertWithError:error];
//    }];
//}


+ (TheGlobalMethod *)main {
    static TheGlobalMethod *geRen = nil;
    if (geRen == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            geRen = [[TheGlobalMethod alloc] init];
        });
    }
    
    return geRen;
}



@end
